package com.nobuyme.box.toy.manage;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.nobuyme.box.R;
import com.nobuyme.box.account.Account;
import com.nobuyme.box.account.AccountManager;
import com.nobuyme.box.app.UrlCenter;
import com.nobuyme.box.bean.UpdataStateEvent;
import com.nobuyme.box.toy.ToyListFragment;
import com.nobuyme.box.toy.ToyManageListActivity;
import com.nobuyme.box.util.DriveControlLattice;
import com.nobuyme.box.util.UICommon;
import com.nobuyme.box.util.UICommon1;
import com.nobuyme.box.xunfei.XunFeiSpeech;
import com.pachong.android.baseuicomponent.activity.BaseActivity;
import com.pachong.android.framework.httprequest.HttpRequest;
import com.pachong.android.framework.httprequest.responsecallbacks.DataRequestListener;
import com.pachong.android.frameworkbase.dialog.AlertDialogFragment;
import com.pachong.android.frameworkbase.utils.EasyToast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import android_serialport_api.SerialPortFinder;
import butterknife.Bind;
import butterknife.OnClick;

public class PutGoodsActivity extends BaseActivity {
    @Bind(R.id.iv_top_goods)
    ImageView mIvTopGoods;
    @Bind(R.id.tv_goods_title)
    TextView mTvGoodsTitle;
    @Bind(R.id.tv_goods_state)
    TextView mTvGoodsState;
    @Bind(R.id.btn_null)
    Button mBtnNull;
    @Bind(R.id.rl_null_close)
    RelativeLayout mRlNullClose;
    @Bind(R.id.tv_null_boy)
    TextView mTvNullBoy;
    @Bind(R.id.iv_goods_content)
    ImageView mIvGoodsContent;
    @Bind(R.id.tv_goods_content)
    TextView mTvGoodsContent;
    @Bind(R.id.tv_goods_content_id)
    TextView mTvGoodsContentId;
    @Bind(R.id.rl_goods_content)
    RelativeLayout mRlGoodsContent;
    @Bind(R.id.btn_put_complete)
    Button mBtnPutComplete;
    @Bind(R.id.tv_put_cancel)
    TextView mTvPutCancel;
    private ToyListFragment.TestBean data;
    private SerialPortFinder mSerialPortFinder;
    private TextView m_test_result = null;
    private int position;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        hideToolbar();
        data = (ToyListFragment.TestBean) getIntent().getSerializableExtra("data");
        position = getIntent().getIntExtra("position", -1);
        initData();

        mSerialPortFinder = UICommon.getInstance().getSerialPortFinder();
        Account acc = AccountManager.getCurrentAccount();
        //开柜
        openLattice(acc.getId(), acc.getPolling_one(), acc.getPolling_two(), acc.getPolling_three(), acc.getPolling_four(), position);

        String[] entries = null;
        String[] entryValues = null;
        if (mSerialPortFinder != null) {
            entries = mSerialPortFinder.getAllDevices();
            entryValues = mSerialPortFinder.getAllDevicesPath();
            if (entries != null) {
                for (String ss : entries) {
                }
            }
            if (entryValues != null) {
                for (String ss : entryValues) {
                }
            }
        }
    }

    //开柜方法
    public static void openLattice(int id, int polling_one, int polling_two, int polling_three, int polling_four, int position) {
        //万科柜子、串口1的 17打不开。18打开的是17     19打开18

        if (id == 2) {
            if (position >= 17 && position <= 20) {
                UICommon.getInstance().writeData(DriveControlLattice.getInstance().LatticeOnOff(polling_two + "", position + 1));
            } else {
                if (position >= 1 && position <= 20) {
                    UICommon.getInstance().writeData(DriveControlLattice.getInstance().LatticeOnOff(polling_one + "", position));
                } else if (position >= 21 && position <= 40) {
                    UICommon.getInstance().writeData(DriveControlLattice.getInstance().LatticeOnOff(polling_two + "", position - 20));
                } else if (position >= 41 && position <= 60) {
                    UICommon1.getInstance().writeData(DriveControlLattice.getInstance().LatticeOnOff(polling_three + "", position - 40));
                } else if (position >= 61 && position <= 80) {
                    UICommon1.getInstance().writeData(DriveControlLattice.getInstance().LatticeOnOff(polling_four + "", position - 60));
                }
            }
            //绿苑海景柜子
        } else if(id == 16){
            if (position >= 21 && position <= 40) {
                UICommon.getInstance().writeData(DriveControlLattice.getInstance().LatticeOnOff(polling_two + "", position-20 - 1));
            } else {
                if (position >= 1 && position <= 20) {
                    UICommon.getInstance().writeData(DriveControlLattice.getInstance().LatticeOnOff(polling_one + "", position));
                } else if (position >= 41 && position <= 60) {
                    UICommon1.getInstance().writeData(DriveControlLattice.getInstance().LatticeOnOff(polling_three + "", position - 40));
                } else if (position >= 61 && position <= 80) {
                    UICommon1.getInstance().writeData(DriveControlLattice.getInstance().LatticeOnOff(polling_four + "", position - 60));
                }
            }

        }else {
            if (position >= 1 && position <= 20) {
                UICommon.getInstance().writeData(DriveControlLattice.getInstance().LatticeOnOff(polling_one + "", position));
            } else if (position >= 21 && position <= 40) {
                UICommon.getInstance().writeData(DriveControlLattice.getInstance().LatticeOnOff(polling_two + "", position - 20));
            } else if (position >= 41 && position <= 60) {
                UICommon1.getInstance().writeData(DriveControlLattice.getInstance().LatticeOnOff(polling_three + "", position - 40));
            } else if (position >= 61 && position <= 80) {
                UICommon1.getInstance().writeData(DriveControlLattice.getInstance().LatticeOnOff(polling_four + "", position - 60));
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    //管理员扫描产品上货
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(UpdataStateEvent updataStateEvent) {
        mTvNullBoy.setVisibility(View.GONE);
        mRlGoodsContent.setVisibility(View.VISIBLE);
        Glide.with(this).load(updataStateEvent.imgUrl).into(mIvGoodsContent);
        mTvGoodsContent.setText(updataStateEvent.name);
        mTvGoodsContentId.setText("商品ID:" + updataStateEvent.id);
        //设置上货完成可点击
        if (updataStateEvent.name != null) {
            mBtnPutComplete.setTextColor(Color.parseColor("#301112"));
            mBtnPutComplete.setEnabled(true);
        } else {
            EasyToast.showToast(PutGoodsActivity.this, "暂无商品");
        }
    }

    public void initData() {
        Account acc = AccountManager.getCurrentAccount();
        try {
            XunFeiSpeech xunFeiSpeech = new XunFeiSpeech(this);
            xunFeiSpeech.speak("12", position + "号储物格已打开,操作完成请关柜门", new XunFeiSpeech.OnCompleteListener() {
                @Override
                public void onComplete() {
//                    EasyToast.showToast(PutGoodsActivity.this,"柜门已打开");
                }
            });
        } catch (NullPointerException e) {

        }
        mTvGoodsTitle.setText(data.getName());
        mTvGoodsState.setText(position + "号储物格已打开");
        mBtnNull.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mRlNullClose.setVisibility(View.INVISIBLE);
            }
        });

    }


    public static void start(Activity activity, ToyListFragment.TestBean data, int position) {
        Intent intent = new Intent(activity, PutGoodsActivity.class);
        intent.putExtra("data", data);
        intent.putExtra("position", position);
        activity.startActivity(intent);
    }

    @Override
    public View createDataView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.activity_put_goods, null);
    }

    @OnClick({R.id.btn_put_complete, R.id.btn_put_cancel, R.id.tv_put_cancel})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_put_complete:
                //上货完成更改状态
                mRlNullClose.setVisibility(View.VISIBLE);
                //确定上货
                mBtnNull.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        setStateId();
                    }
                });
                //取消上货
                mTvPutCancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mRlNullClose.setVisibility(View.INVISIBLE);
                    }
                });
                break;
            case R.id.btn_put_cancel:
                //取消上架
                try {
                    XunFeiSpeech xunFeiSpeech = new XunFeiSpeech(this);
                    xunFeiSpeech.speak("12", "未上架新玩具，请关"+position+"号储物格", new XunFeiSpeech.OnCompleteListener() {
                        @Override
                        public void onComplete() {
//                    EasyToast.showToast(PutGoodsActivity.this,"柜门已打开");
                        }
                    });
                } catch (NullPointerException e) {
                }
                ToyManageListActivity.start(PutGoodsActivity.this,0);
                finish();
                //暂放一下
//             ShowCloseLatted();
                break;
        }
    }

    private void ShowCloseLatted() {
        final AlertDialogFragment dialogOutFragment = new AlertDialogFragment();
        dialogOutFragment.setMessage("记得关闭储物格哦~").setNegativeButton("好的", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                dialogOutFragment.dismiss();
            }
        });
    }

    private void setStateId() {
        HttpRequest request = new HttpRequest(this);
        JSONObject jobj = new JSONObject();
        try {
//            jobj.put("latticeId",data.getLattice_id());
            jobj.put("type", 1);
            String s = String.format(UrlCenter.PUT_GOODS, data.getLattice_id());
            String urlPut = s + "?type=1";
            request.put(urlPut, null, new DataRequestListener<Object>(Object.class) {
                @Override
                public void onStart(Context context, String url) {
                    super.onStart(context, url);
                }

                @Override
                public void onSuccess(Object o) {
                    super.onSuccess(o);
                    EasyToast.showToast(PutGoodsActivity.this, "上货成功");
                    ToyManageListActivity.start(PutGoodsActivity.this,0);
                    finish();
                }

                @Override
                public void onFailure(Throwable t, int errorNo, String strMsg) {
                    super.onFailure(t, errorNo, strMsg);
                    EasyToast.showToast(PutGoodsActivity.this, strMsg);
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }




}
